package com.lfp.controller;

import com.lfp.config.rabbitmq.TtlQueueConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2022/3/29 22:48
 * @Version 1.0
 */

@Slf4j
@RestController
@Api(tags = "延时队列消息")
@RequestMapping("/ttl")
public class TTLQueueController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ApiOperation("延时-死信队列消息发送")
    @PostMapping("/sendMessage/{message}")
    public void sendMessage(@PathVariable String message){
        //通过confirm_exchange 交换机，使用“XA”、“XB”发信息
        rabbitTemplate.convertAndSend(TtlQueueConfig.X_EXCHANGE,
                TtlQueueConfig.ROUTING_KEY_XEXCHANGE_TO_QUEUEA,message.getBytes());

        rabbitTemplate.convertAndSend(TtlQueueConfig.X_EXCHANGE,
                TtlQueueConfig.ROUTING_KEY_XEXCHANGE_TO_QUEUEB,message.getBytes());
        log.info("延时队列消息已发送，内容为：{}",message);
    }

    @ApiOperation("动态发送过期时间消息")
    @PostMapping("sendExpirationMsg/{message}/{ttlTime}")
    public void sendExpirationMsg(@PathVariable("message")String message,
                                  @PathVariable("ttlTime") String ttlTime){

        rabbitTemplate.convertAndSend(
                TtlQueueConfig.X_EXCHANGE,
                TtlQueueConfig.ROUTING_KEY_XEXCHANGE_TO_QUEUEC,
                message.getBytes(),
                message1 -> {//通过Lambda表达式方式，给消息设置存活（过期）时间
                    message1.getMessageProperties().setExpiration(ttlTime);
                    return message1;
                });

        log.info("发送一条时长为:{}毫秒的TTL消息，消息内容为：{}",ttlTime,message);
    }
}
